package com.csu.wxprogram.controller;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;

import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* @author zhenhua.chun 
* @version 2016年11月15日 下午3:50:52
* @Description
*/
@RestController
@RequestMapping("/webSocketUrl")
public class WebSocketController {
	private static Logger log = Logger.getLogger(WebSocketController.class);
	
	private static int onlineCount = 0;  
	  
    private static CopyOnWriteArraySet<WebSocketController> webSocketSet = new CopyOnWriteArraySet<>();  
  
    private Session session;  
  
    @OnOpen  
    @RequestMapping("/online")
    public void onOpen (Session session,String name){  
        this.session = session; 
        webSocketSet.add(this);  
        addOnlineCount();  
        System.out.println("有新链接加入!当前在线人数为" + getOnlineCount());  
    }  
  
    @OnClose  
    @RequestMapping("/offline")
    public void onClose (){  
        webSocketSet.remove(this);  
        subOnlineCount();  
        System.out.println("有一链接关闭!当前在线人数为" + getOnlineCount());  
    }  
  
    @OnMessage
    @RequestMapping("/sendMessageToAll")
    public void onMessage (String message, Session session) throws IOException {  
        System.out.println("来自客户端的消息:" + message);  
        // 群发消息  
        for ( WebSocketController item : webSocketSet ){  
                item.sendMessage(message);  
        }  
    }  
    @RequestMapping("/sendMessage")
    public void sendMessage (String message) throws IOException {  
        this.session.getBasicRemote().sendText(message);  
    }  
  
    public static synchronized  int getOnlineCount (){  
        return WebSocketController.onlineCount;  
    }  
  
    public static synchronized void addOnlineCount (){  
    	WebSocketController.onlineCount++;  
    }  
  
    public static synchronized void subOnlineCount (){  
    	WebSocketController.onlineCount--;  
    }  
}
